﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using Unity;
using Unity.Lifetime;

namespace FlowDesigner.Containerfot
{
    /// <summary>
    /// 
    /// </summary>
    public class Container
    {

        public static  IUnityContainer container = new UnityContainer();
        /// <summary>
        /// 添加服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="T1"></typeparam>
        /// <param name="t"></param>
        /// <param name="t1"></param>
        public static void AddRegisterType(Type t)
        {
            // 注册 View，并设置 ViewModel 的依赖注入单列模式
            container.RegisterType(t, t.Name, new ContainerControlledLifetimeManager());
            //container.RegisterType(t,t1);
        }
        public static UserControl GetRegisterType(Type type)
        {
            var d = container.Registrations.FirstOrDefault(t => t.Name == type.Name);
            if (d != null && d.Name == type.Name)
            {
                var View = container.Resolve(type) as UserControl;
                View.DataContext = container.Resolve(container.Registrations.FirstOrDefault(t => t.Name == $"{type.Name}Model").RegisteredType);
                return View;
            }
            return null;
        }
        /// <summary>
        /// 装载部件
        /// </summary>
        public static void Loadparts()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            // 获取程序集中定义的所有类型
            Type[] types = assembly.GetTypes();
            // 筛选出属于目标命名空间的类型
            Type[] typesInNamespace = types
                .Where(t => t.Namespace != null && (t.Namespace.Contains("View") || t.Namespace.Contains("ViewModel")))
                .ToArray();
            foreach (Type type in typesInNamespace)
            {
                string typeDescription = GetTypeDescription(type);

            }
        }
        /// <summary>
        /// 获取类型的描述信息
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns>描述信息</returns>
        public  static  string GetTypeDescription(Type type)
        {
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(type, typeof(DescriptionAttribute)) as DescriptionAttribute;

            return attribute != null ? attribute.Description : type.Name;
        }

    }
}
